//
//  WKSettingsController.m
//  WeKeTang
//
//  Created by ichina on 2017/8/31.
//  Copyright © 2017年 Dezhi Tiancheng Education Technology (Beijing) Co. Ltd. All rights reserved.
//

#import "WKSettingsController.h"
#import "WKNavgationController.h"
#import "WKAboutWeKeTangController.h"
#import "WKChangePasswordController.h"
#import "WKLoginViewController.h"
#import "ScottAlertController.h"
#import "WKAlerView.h"
#import "WKTableViewCell.h"
#import "AppDelegate.h"
#import "WKLoginHandel.h"
#import "WKAlerView.h"
#import "WKUniversal.h"
#import <SDImageCache.h>
@interface WKSettingsController ()<UITableViewDelegate,UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UITableView *mainTableView;

@property (nonatomic, strong) NSArray *titles;

@property (weak, nonatomic) IBOutlet UIButton *btnExitLogin;

@property (nonatomic, strong) WKAlerView *alertView;

@property (nonatomic, strong) YYLabel *rightLabel;



@end

@implementation WKSettingsController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupUI];
}
- (void)setupUI{
    
    self.navItem.title = @"设置";
    
    self.navgationBar.barTintColor = RGBColor(40, 188, 203);
    
    self.statusbar.backgroundColor = RGBColor(40, 188, 203);
    
    [self middleTitleColor:[UIColor whiteColor]];
    
    self.view.backgroundColor = RGBColor(245, 245, 245);
    self.mainTableView.backgroundColor = RGBColor(245, 245, 245);
    [self setLeftButtonWithImage:@"icon_return_white" highlightedImage:@"icon_return_white" target:self action:@selector(backAction)];
    self.titles = @[@"允许使用3G/4网络观看视频",@"允许使用3G/4网络下载视频",@"清除缓存",@"修改密码",@"版本号",@"关于微课堂"];
    self.btnExitLogin.layer.borderColor = RGBColor(230, 230, 230).CGColor;
    self.btnExitLogin.layer.borderWidth = 0.5;
    self.btnExitLogin.layer.cornerRadius = 2;
    self.btnExitLogin.layer.masksToBounds = YES;
    [self.mainTableView registerClass:[WKTableViewCell class] forCellReuseIdentifier:@"ExpireCell"];
    self.mainTableView.separatorColor = RGBColor(240, 240, 240);
    self.mainTableView.tableFooterView = [[UIView alloc]init];

}
#pragma mark - 数据源方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 6;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static  NSString *cellIdentifier = @"ExpireCell";
    WKTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        
        cell = [[WKTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.tag = indexPath.row;
    cell.backgroundColor = [UIColor whiteColor];
    YYLabel *leftLabel = [[YYLabel alloc]initWithFrame:CGRectMake(15, 0, 200, 44)];
    leftLabel.font = [UIFont systemFontOfSize:15];
    leftLabel.textColor = [UIColor blackColor];
    leftLabel.text = self.titles[indexPath.row];
    [cell.contentView addSubview:leftLabel];
    if (indexPath.row == 0) {
        UIButton *watchBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        watchBtn.frame = CGRectMake(kDeviceScreenWidth-50-15, 15, 50, 44-20);
        [watchBtn setTitle:@"已关闭" forState:UIControlStateNormal];
        [watchBtn setTitle:@"已开启" forState:UIControlStateSelected];
        [watchBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        watchBtn.titleLabel.font = [UIFont systemFontOfSize:13];
        BOOL isStart = [[NSUserDefaults standardUserDefaults]objectForKey:@"watch"];
        if (isStart) {
            watchBtn.selected = YES;
            watchBtn.backgroundColor = RGBColor(43, 187, 203);
        }else{
            watchBtn.selected = NO;
            watchBtn.backgroundColor = RGBColor(213, 213, 213);
        }
        [watchBtn addTarget:self action:@selector(watchBtnAction:) forControlEvents:UIControlEventTouchUpInside];
        [cell.contentView addSubview:watchBtn];
        
    }else if (indexPath.row == 1){
        UIButton *downLoadBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        downLoadBtn.frame = CGRectMake(kDeviceScreenWidth-50-15, 10, 50, 44-20);
        [downLoadBtn setTitle:@"已关闭" forState:UIControlStateNormal];
        [downLoadBtn setTitle:@"已开启" forState:UIControlStateSelected];
        [downLoadBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        downLoadBtn.titleLabel.font = [UIFont systemFontOfSize:13];
        BOOL isStart = [[NSUserDefaults standardUserDefaults]objectForKey:@"downLoad"];
        if (isStart) {
            downLoadBtn.selected = YES;
            downLoadBtn.backgroundColor = RGBColor(43, 187, 203);
        }else{
            downLoadBtn.selected = NO;
            downLoadBtn.backgroundColor = RGBColor(213, 213, 213);
        }
        [downLoadBtn addTarget:self action:@selector(downLoadBtnAction:) forControlEvents:UIControlEventTouchUpInside];
        [cell.contentView addSubview:downLoadBtn];
        
    }else if (indexPath.row == 2){
        UIImageView *allowImgView = [[UIImageView alloc]initWithFrame:CGRectMake(kDeviceScreenWidth-7-15, (44-12)*0.5, 7, 12)];
        allowImgView.image = IMG(@"icon_right_allow");
        [cell.contentView addSubview:allowImgView];
        self.rightLabel = [[YYLabel alloc]initWithFrame:CGRectMake(kDeviceScreenWidth-7-15-80-8, 0, 80, 44)];
        self.rightLabel.textColor = [UIColor colorWithHexString:@"#666666"];
        self.rightLabel.text = _S(@"%.2fM",[self folderSize]);
        self.rightLabel.textAlignment = NSTextAlignmentRight;
        self.rightLabel.font = [UIFont systemFontOfSize:13];
        [cell.contentView addSubview:self.rightLabel];
        
    }else if (indexPath.row == 3){
        
        UIImageView *allowImgView = [[UIImageView alloc]initWithFrame:CGRectMake(kDeviceScreenWidth-7-15, (44-12)*0.5, 7, 12)];
        allowImgView.image = IMG(@"icon_right_allow");
        [cell.contentView addSubview:allowImgView];
        
    }else if (indexPath.row == 4){
        
        YYLabel *rightLabel = [[YYLabel alloc]initWithFrame:CGRectMake(kDeviceScreenWidth-80-15, 0, 80,44)];
        rightLabel.textColor = [UIColor colorWithHexString:@"#666666"];
        rightLabel.text = @"V1.0.0";
        rightLabel.textAlignment = NSTextAlignmentRight;
        rightLabel.font = [UIFont systemFontOfSize:13];
        [cell.contentView addSubview:rightLabel];
        
    }else{
        
        UIImageView *allowImgView = [[UIImageView alloc]initWithFrame:CGRectMake(kDeviceScreenWidth-7-15, (44-12)*0.5, 7, 12)];
        allowImgView.image = IMG(@"icon_right_allow");
        [cell.contentView addSubview:allowImgView];

    }
    
    return cell;
}
#pragma mark - 代理方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    __weak typeof(self) weakSelf = self;
    if (indexPath.row == 2) {
        //清除缓存
        self.alertView = [[WKAlerView alloc]initWithFrame:CGRectMake(0, 0, kDeviceScreenWidth, kDeviceScreenHeight) message:@"确定要清除缓存" tip:@"清除缓存后不会删除已下载的课程。" title1:@"取消" title2:@"确定"];
        self.alertView.confirmBlock = ^{
            //取消
            [weakSelf.alertView removeFromSuperview];
        };
        self.alertView.cancelBlock = ^{
            //确定
            [weakSelf removeCache];
            [weakSelf.alertView removeFromSuperview];
        };
        self.alertView.deleteBlock = ^{
            //删除
            [weakSelf.alertView removeFromSuperview];
        };
        [[AppDelegate shareDelegate].window addSubview:self.alertView];
    }else if (indexPath.row == 3){
        //修改密码
        WKChangePasswordController *changeVC = [[WKChangePasswordController alloc]init];
        
        [self.navigationController pushViewController:changeVC animated:YES];
        
    }else if (indexPath.row == 5){
        //关于微课堂
        WKAboutWeKeTangController *aboutVC = [[WKAboutWeKeTangController alloc]init];
        
        [self.navigationController pushViewController:aboutVC animated:YES];
    }
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 44;
}
#pragma mark - 允许观看3/4G视频
- (void)watchBtnAction:(UIButton*)sender{
    
    sender.selected = !sender.selected;
    
    if (sender.selected) {
        [[NSUserDefaults standardUserDefaults]setBool:YES forKey:@"watch"];
        [[NSUserDefaults standardUserDefaults]synchronize];
        sender.backgroundColor= RGBColor(43, 187, 203);
        [sender setTitle:@"已开启" forState:UIControlStateNormal];
        
    }else{
        [[NSUserDefaults standardUserDefaults]removeObjectForKey:@"watch"];
        [[NSUserDefaults standardUserDefaults]synchronize];
        sender.backgroundColor= RGBColor(213, 213, 213);
        [sender setTitle:@"已关闭" forState:UIControlStateNormal];
    }
}
#pragma mark - 允许下载3/4G视频
- (void)downLoadBtnAction:(UIButton*)sender{
    sender.selected = !sender.selected;
    
    if (sender.selected) {
        [[NSUserDefaults standardUserDefaults]setBool:YES forKey:@"downLoad"];
        [[NSUserDefaults standardUserDefaults]synchronize];
        sender.backgroundColor= RGBColor(43, 187, 203);
        [sender setTitle:@"已开启" forState:UIControlStateNormal];
    }else{
        [[NSUserDefaults standardUserDefaults]removeObjectForKey:@"downLoad"];
        [[NSUserDefaults standardUserDefaults]synchronize];

        sender.backgroundColor= RGBColor(213, 213, 213);
        [sender setTitle:@"已关闭" forState:UIControlStateNormal];
    }
    
}
#pragma mark - 退出登录
- (IBAction)btnExitLoginAction:(UIButton *)sender {
    
        
     ScottAlertView *alertView = [ScottAlertView alertViewWithTitle:@"您确认退出微课堂么?" message:@""];
     [alertView addAction:[ScottAlertAction actionWithTitle:@"取消" style:ScottAlertActionStyleCancel handler:^(ScottAlertAction *action) {
     
     }]];
     
     [alertView addAction:[ScottAlertAction actionWithTitle:@"确定" style:ScottAlertActionStyleDestructive handler:^(ScottAlertAction *action) {
     
         WKLoginViewController *loginVC = [[WKLoginViewController alloc]init];
         WKNavgationController *navVC = [[WKNavgationController alloc]initWithRootViewController:loginVC];
         //删除登录时的数据
         [WKLoginHandel removeLoginData];
         [WKUniversal removeImgData];
//         [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"account"];
//         [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"psd"];
         [[NSUserDefaults standardUserDefaults]setObject:@"" forKey:@"account"];
         [[NSUserDefaults standardUserDefaults]setObject:@"" forKey:@"psd"];
         [[NSUserDefaults standardUserDefaults]synchronize];
         NSLog(@"%@",[[NSUserDefaults standardUserDefaults]objectForKey:@"account"]);
         NSLog(@"%@",[[NSUserDefaults standardUserDefaults]objectForKey:@"psd"]);
         
         [AppDelegate shareDelegate].window.rootViewController = navVC;
     }]];
     
     ScottAlertViewController *alertController = [ScottAlertViewController alertControllerWithAlertView:alertView preferredStyle:ScottAlertControllerStyleAlert transitionAnimationStyle:ScottAlertTransitionStyleDropDown];
     alertController.tapBackgroundDismissEnable = YES;
     [self presentViewController:alertController animated:YES completion:nil];
    
   }

#pragma mark - 返回
- (void)backAction:(UIButton*)sender{
    
    [self dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark - 缓存大小
- (CGFloat)folderSize{
    
    CGFloat folderSize = 0.0;
    //获取路径
    NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES)firstObject];
    //获取所有文件的数组
    NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:cachePath];
    
    for(NSString *path in files) {
        
        NSString*filePath = [cachePath stringByAppendingString:[NSString stringWithFormat:@"/%@",path]];
        //累加
        folderSize += [[NSFileManager defaultManager]attributesOfItemAtPath:filePath error:nil].fileSize;
    }
    //转换为M为单位
    CGFloat sizeM = folderSize /1024.0/1024.0;
    return sizeM;
}
- (void)removeCache{
    //获取路径
    
    NSString*cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES)objectAtIndex:0];
    //返回路径中的文件数组
    NSArray*files = [[NSFileManager defaultManager]subpathsAtPath:cachePath];
    NSLog(@"文件数：%ld",[files count]);
    for(NSString *p in files){
        NSError*error;
        NSString*path = [cachePath stringByAppendingString:[NSString stringWithFormat:@"/%@",p]];
        if([[NSFileManager defaultManager]fileExistsAtPath:path]){
            BOOL isRemove = [[NSFileManager defaultManager]removeItemAtPath:path error:&error];
            if(isRemove) {
                NSLog(@"清除成功");
                [self showCustomAlertMessage:@"清除成功"];
                [self.mainTableView reloadData];
                self.rightLabel.text = @"";
                NSLog(@"清除:%@",self.rightLabel.text);
            }else{
                NSLog(@"清除失败");
            }
        }
    }
}

@end
